package com.example.applicationview.viewgroup;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

/**
 * 演示viewGroup通过onInterceptTouchEvent 拦截事件（向不向子view传递）
 */
public class MyViewGroup extends LinearLayout {

    float downX = 0;
    float downY = 0;

    public MyViewGroup(Context context) {
        this(context, null);
    }

    public MyViewGroup(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }


    //重写父容器的拦截方法
    public boolean onInterceptTouchEvent (MotionEvent event){
        boolean intercepted = false;
        float x = event.getX();
        float y =  event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN://对于ACTION_DOWN事件必须返回false，一旦拦截后续事件将不能传递给子View
                downX = x;
                downY = y;
                intercepted = false;
                Log.d("message","ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE://对于ACTION_MOVE事件根据需要决定是否拦截
                Log.d("message","ACTION_MOVE");
                intercepted = false;
                                //左右滑动
                if(getAbsoluteValue(x- downX) >= getAbsoluteValue(y- downY)){
                    if(x >= downX){
                        //右滑
                        Log.d("message","右滑");
                    }else {
                        //左滑
                        Log.d("message","左滑");
                        intercepted = true;
                    }
                }
                //上下滑动
                else {
                    if(y >= downY){
                        //右滑
                        Log.d("message","下滑");
                    }else {
                        //左滑
                        Log.d("message","上滑");
                    }
                }

            break;
        case MotionEvent.ACTION_UP://对于ACTION_UP事件必须返回false，一旦拦截子View的onClick事件将不会触发
            Log.d("message","ACTION_UP");
        intercepted = false;
        break;
        default :
            break;
    }
    return intercepted;
}

    private  float getAbsoluteValue(float value) {
        return (value < 0) ? -value : value;
    }



}
